package com.bnlr.lrparking.appui.mine.collection.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.carplace.CarPlaceDetailActivity;
import com.bnlr.lrparking.adapter.HeaderAndFooterRecyclerViewAdapter;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.CarPlaceData;
import com.bnlr.lrparking.model.MyCollectM;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.widget.NativeDialog;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 *
 *
 * A simple {@link Fragment} subclass.
 * @author tian
 */
public class ParkingCollectFragment extends BaseFragment {
    private Unbinder unbinder;

    @BindView(R.id.lv_mycar_list)
    RecyclerView lvMycarList;
    @BindView(R.id.rl_mycar_refresh)
    XRefreshLayout rlMycarRefresh;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    List<CarPlaceData> myCollectList = new ArrayList<>();
    public LinearLayoutManager linearLayoutManager;
    public boolean isLoadingMore;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parking_collect, container, false);
        unbinder = ButterKnife.bind(this,view);
        initView();
        return view;
    }
    @Override
    public void onResume() {
        super.onResume();
        footView.setVisibility(View.GONE);
        llHint.setVisibility(View.GONE);
        if (myCollectList.size() > 0) {
            myCollectList.clear();
            adapter.notifyDataSetChanged();
        }
        pageNum = 1;
        getData();
    }

    private View footView;
    private TextView tv_foot;
    private MyCarAdapter adapter;
    private void initView() {
        llHint.setVisibility(View.GONE);
        footView = View.inflate(getActivity(), R.layout.layout_footview, null);
        tv_foot = (TextView) footView.findViewById(R.id.tv_foot);
        footView.setVisibility(View.GONE);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        lvMycarList.setLayoutManager(linearLayoutManager);
        lvMycarList.setItemAnimator(new DefaultItemAnimator());
        adapter = new MyCarAdapter(getActivity(), R.layout.item_search, myCollectList);
        headerAndFooterAdapter = new HeaderAndFooterRecyclerViewAdapter(adapter);
        headerAndFooterAdapter.addFooterView(footView);
        lvMycarList.setAdapter(headerAndFooterAdapter);
        rlMycarRefresh.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(getActivity()));
        rlMycarRefresh.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                footView.setVisibility(View.GONE);
                llHint.setVisibility(View.GONE);
                if (myCollectList.size() > 0) {
                    myCollectList.clear();
                    adapter.notifyDataSetChanged();
                }
                pageNum = 1;
                getData();
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }

        });

        lvMycarList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int total = linearLayoutManager.getItemCount();
                int lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
                // dy > 0 表示向下滑动
                if (lastVisibleItem >= total - 2 && dy > 0) {
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        getData();
                    }
                }
            }
        });

        lvMycarList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return rlMycarRefresh.isRefreshing();
            }
        });
    }
    @Override
    public void getData() {
        super.getData();
        try {
            if (CommonUtil.isNetworkAvailable(getActivity()) == 0) {
                CommonUtil.showToask(getActivity(), "当前无网络连接，请检查网络设置");
                return;
            }
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetParkByUser");
            mRequest.add("uid", AppConfig.getInstance().getString("uid",""));
            mRequest.add("lng", Params.CurrentLon);
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("lat", Params.CurrentLat);
            mRequest.add("index", pageNum);
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<MyCollectM>(getActivity(), true, MyCollectM.class) {

                        @Override
                        public void doWork(MyCollectM data, String code) {
                            if ("1".equals(code)) {
                                if (pageNum != 1) {
                                    if (data.getData().size() < 10) {
                                        footView.setVisibility(View.VISIBLE);
                                        tv_foot.setText(R.string.foot_all);
                                    } else {
                                        footView.setVisibility(View.VISIBLE);
                                        tv_foot.setText(R.string.foot_more);
                                    }
                                }
                                pageNum++;
                                myCollectList.addAll(data.getData());
                                for (int i=0;i<myCollectList.size();i++){
                                    myCollectList.get(i).setIsFavorite("1");
                                }
                                adapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (rlMycarRefresh != null) {
                                rlMycarRefresh.endRefreshing();
                            }
                            isLoadingMore = false;
                            if (myCollectList.size() == 0) {
                                llHint.setVisibility(View.VISIBLE);
                                ivHint.setBackgroundResource(R.mipmap.nocollection);
                                tvHintTips.setText("您还没有收藏，快去把您常用的\n           停车场收入囊中吧~");
                            } else {
                                llHint.setVisibility(View.GONE);
                                if (!TextUtils.equals("1", code) && pageNum != 1) {
                                    footView.setVisibility(View.VISIBLE);
                                    tv_foot.setText(R.string.foot_all);
                                }
                            }
                        }
                    }, false);
        }catch (Exception e){
        }
    }

    public class MyCarAdapter extends CommonAdapter<CarPlaceData> {

        public MyCarAdapter(Context context, int layoutId, List<CarPlaceData> datas) {
            super(context, layoutId, datas);
        }

        @Override
        protected void convert(ViewHolder holder, final CarPlaceData s, int position) {
            LikeButton likeButton=holder.getView(R.id.likeButton);
            LinearLayout lay_info= holder.getView(R.id.lay_carplace_info);
            LinearLayout lay_daohang= holder.getView(R.id.lay_daohang);
            LinearLayout lay_phone= holder.getView(R.id.lay_phone);
            final  TextView tv_collect=holder.getView(R.id.tv_collect);
            holder.setText(R.id.tv_carplace_name,s.getName());
            holder.setText(R.id.tv_car_juli,""+s.getJuli());
            holder.setText(R.id.tv_car_time,s.getSharevalue()+"共享值/小时");
            holder.setText(R.id.tv_car_xiaohao,"空车位："+s.getChewei());
            holder.setText(R.id.tv_car_price,"车位价格：" + s.getMinsellingprice());
            holder.setText(R.id.tv_car_number,"" + s.getSellingcount());
            String phone=s.getPhone();
            if(TextUtils.isEmpty(phone)){
                phone="暂无";
            }
            holder.setText(R.id.tv_phone,"电话："+phone);
            holder.setText(R.id.tv_address,"地址："+s.getAddress());
            if("0".equals(s.getIsjoin())){
                holder.setVisible(R.id.tv_mianfei,true);
                holder.setText(R.id.tv_car_kong,"开放时间："+s.getOpentime());
                holder.setVisible(R.id.tv_car_kong,true);
                holder.setVisible(R.id.tv_jiamengzhong,false);
                lay_info.setVisibility(View.VISIBLE);

            }else{
                holder.setVisible(R.id.tv_mianfei,false);
                holder.setText(R.id.tv_car_kong,"开放时间：全天24小时");
                holder.setVisible(R.id.tv_car_kong,true);
                holder.setVisible(R.id.tv_jiamengzhong,true);
                lay_info.setVisibility(View.GONE);
            }
            likeButton.setLiked(true);
            tv_collect.setTextColor(getResources().getColor(R.color.main_color));
            lay_daohang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Location loc_now = new Location(Params.CurrentLat, Params.CurrentLon, "s");
                    Location loc_end = new Location(Double.valueOf(s.getLat()), Double.valueOf(s.getLng()), "e");
                    NativeDialog msgDialog = new NativeDialog(getActivity(), loc_now, loc_end);
                    msgDialog.show();

                }
            });

            lay_phone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(TextUtils.isEmpty(s.getPhone())){
                        CommonUtil.showToask(getActivity(),"暂无电话，无法拨打！");
                    }else {
                        CarCommon carCommon = new CarCommon();
                        carCommon.phoneDialog(getActivity());
                    }

                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(getActivity(),CarPlaceDetailActivity.class);
                    intent.putExtra("lat",s.getLat());
                    intent.putExtra("lon",s.getLng());
                    intent.putExtra("CarPlace",s);
                    startActivity(intent);
                }
            });
            likeButton.setOnLikeListener(new OnLikeListener() {
                @Override
                public void liked(LikeButton likeButton) {
                    SendCollect(s.getId());
                    tv_collect.setTextColor(getResources().getColor(R.color.main_color));
                }
                @Override
                public void unLiked(LikeButton likeButton) {
                    SendCollect(s.getId());
                    tv_collect.setTextColor(getResources().getColor(R.color.black_color));
                }
            });
        }
    }
    private void SendCollect(String carplaceid) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "SetFavorite");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid",""));
            mRequest.add("parkId", carplaceid);
            // 添加到请求队列
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<JSONObject>(getActivity(), false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    footView.setVisibility(View.GONE);
                                    llHint.setVisibility(View.GONE);
                                    if (myCollectList.size() > 0) {
                                        myCollectList.clear();
                                        adapter.notifyDataSetChanged();
                                    }
                                    pageNum = 1;
                                    getData();
                                } else {
                                    CommonUtil.showToask(getActivity(), obj.getString("msg"));
                                }


                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }
}
